var Main = cc.Class({
  extends: cc.Component,

  properties: () => ({
    // 卷轴动画
    reelAnimation: {
      default: null,
      type: require("ReelAnimation")
    },
    // 关卡索引数据
    levelData: {
      default: null,
      type: require("LevelData")
    },
    dataNode: {
      default: null,
      type: cc.Node
    },
    paneTop: {
      default: null,
      type: cc.Node
    },
    // 最高分
    scoreMaxLab: {
        default: null,
        type: cc.Label
    },
    // 持有金币数
    cashLab: {
        default: null,
        type: cc.Label
    },
    paneStart: {
      default: null,
      type: cc.Node
    },
    paneLv1st: {
      default: null,
      type: require("LevelAnimation")
    },
    paneLv2nd: {
      default: null,
      type: cc.Node
    },
    paneLv3rd: {
      default: null,
      type: cc.Node
    },
    loadingCoverNode: {
      default: null,
      type: cc.Node
    },
    loadingCoverAni: {
      default: null,
      type: cc.Animation
    },
    btnLv1: {
      default: null,
      type: cc.Node
    },
    btnLv2: {
      default: null,
      type: cc.Node
    },
    btnLv3: {
      default: null,
      type: cc.Node
    },
    btnP1: {
      default: null,
      type: cc.Node
    },
    btnP2: {
      default: null,
      type: cc.Node
    },
    btnP3: {
      default: null,
      type: cc.Node
    },
    textNum: {
      default: null,
      type: cc.Label
    },
    // 子域界面
    paneDisplay: {
      default: null,
      type: cc.Node
    },
    // 子域关闭按钮
    closePaneBtn: {
      default: null,
      type: cc.Node
    },
    // 子域防止穿透节点
    block: {
      default: null,
      type: cc.Node
    },
    // 游戏未开始背景音乐
    mainBgAudio: {
      default: null,
      type: cc.AudioClip
    },
    // 商店界面
    shopDisplay: {
      default: null,
      type: cc.Node
    },
  }),

  onLoad: function() {
    this.shopDisplay.active = false;
    this.closePaneBtn.active = false;
    this.block.active = false;
    cc.audioEngine.play(this.mainBgAudio, true);
    this.btnLv = 0;
    // this.bannerAd = null;

    // 广告接入api
    // let winSize = wx.getSystemInfoSync();
    // let bannerHeight = 80;
    // let bannerWidth = 300;
    // let _bannerAd = wx.createBannerAd({
    //   adUnitId: '11111', //填写广告id
    //   style: {
    //     left: (winSize.windowWidth - bannerWidth)/2,
    //     top: winSize.windowHeight - bannerHeight,
    //     width: bannerWidth,
    //   }
    // });
    // _bannerAd.onLoad(() => {
    //   console.log('banner 广告加载成功')
    // });
    // _bannerAd.show().then(() => console.log('banner 广告显示'));
    // _bannerAd.onResize(res => {_bannerAd.style.top = winSize.windowHeight - _bannerAd.style.realHeight});

    // 广告接入
    // var systemInfo = wx.getSystemInfoSync();
    // this.bannerAd = wx.createBannerAd({
    //   adUnitId: 'adunit-XXX',
    //   style: {
    //     left: 0,
    //     top: systemInfo.windowHeight - 133,
    //     width: 720,
    //   }
    // });
    // var self = this;
    // this.bannerAd.onResize(res => {
    //   self.bannerAd.style.top = systemInfo.windowHeight - self.bannerAd.style.realHeight
    // })
    // this.bannerAd.show();

    // 微信小游戏授权
    var _this = this;
    wx.getSetting({
      success(res) {
        if(res.authSetting['scope.userInfo']) {
          console.log('已经授权下一步是wx.getUserInfo');
          wx.getUserInfo({
            success: res => {
              var userInfo = res.userInfo;
              var nickName = userInfo.nickName;
              var avatarUrl = userInfo.avatarUrl;
              _this.addNickName(_this.paneTop.getChildByName('PlayerName').getComponent(cc.Label), nickName);
              _this.addHeadImg(_this.paneTop.getChildByName('headMask').getChildByName('head').getComponent(cc.Sprite), avatarUrl);
            }
          });
          _this.tex = new cc.Texture2D();
        }else {
          let button = wx.createUserInfoButton({
            type: 'text',
            text: '获取用户信息',
            style: {
              left: 10,
              top: 300,
              width: 200,
              height: 40,
              lineHeight: 40,
              backgroundColor: '#ff0000',
              color: '#ffffff',
              textAlign: 'center',
              fontSize: 16,
              borderRadius: 4
            }
          })
          button.onTap((res) => {
            console.log(button.style.left,res);
            var userInfo = res.userInfo;
            var nickName = userInfo.nickName;
            var avatarUrl = userInfo.avatarUrl;
            _this.addNickName(_this.paneTop.getChildByName('PlayerName').getComponent(cc.Label), nickName);
            _this.addHeadImg(_this.paneTop.getChildByName('headMask').getChildByName('head').getComponent(cc.Sprite), avatarUrl);
            button.style.left = -210;
            _this.tex = new cc.Texture2D();
          })
        }
      }
    });
    // 云
    wx.cloud.init({
      traceUser: true
    });
    // 云函数 获取 openid或者appid
    wx.cloud.callFunction({
      name: 'ganjiangmoye',
      complete: res => {
        // var OPENID = res.result.userInfo.openId;
        _this.OPENID = res.result.userInfo.openId;
        _this.getData(_this.OPENID);
        console.log('云端获取用户数据: ',res.result.userInfo, _this.OPENID);
      }
    });
    // 清除数据时使用
    // wx.removeUserCloudStorage({
    //   keyList: ['score','maxScore','money','totalMoney','tiliNum','zhenqiNum','batiNum'],
    //   success: res => {
    //     console.log("uploadScore success:res=>1", res);
    //   },
    //   fail: res => {
    //     console.log("uploadScore fail:res=>2", res);
    //   },
    //   complete: res => {
    //     console.log("uploadScore complete:res=>3", res);
    //   }
    // })
  },
  // 云端获取用户数据
  getData: function(OPENID) {
    var _this = this;
    console.log("getdata", OPENID);
    const db = wx.cloud.database();
    db.collection('ganjiangmoye').where({
      _openid: OPENID,
    })
    .get({
      success: function(res) {
        // res.data 是一个包含集合中有权限访问的所有记录的数据，不超过 20 条
        if(res.data.length == 0) {
          _this.addData();
          _this.scoreMaxLab.string = '0';
          _this.cashLab.string = '0';
          console.log("getData_success_get长度为0", res.data);
        }else {
          _this._id = res.data[0]._id;
          _this.totalMoney = res.data[0].totalMoney;
          _this.maxScore = res.data[0].maxScore;
          _this.cashLab.string = _this.totalMoney.toString();
          _this.scoreMaxLab.string = _this.maxScore.toString();
          console.log("getData_success_get长度不为0", res.data);
        }
      },
      fail: function(res) {
        console.log("getData_fail_get", res);
      },
      complete: function(res) {
        console.log("getData_complete_get222", res);
      } 
    })
  },
  // 初始化云开发添加数据
  addData: function() {
    // 初始给子域服务端添加
    wx.setUserCloudStorage({
        KVDataList: [{key:'maxScore', value: '0'}],
    });
    // 初始给云数据添加
    const db = wx.cloud.database();
    db.collection('ganjiangmoye').add({
      // data 字段表示需新增的 JSON 数据
      data: {
        totalMoney: 0,
        maxScore: 0,
        tili: 20,
        zhengqi: 20,
        tiliNum: 10,
        zhengqiNum: 10,
        batiNum: 0,
      },
      success: function(res) {
          // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
          console.log('addData_success_add', res);
      },
      fail: function(res) {
          console.log("addData_fail_add", res);
      },
      complete: function(res) {
          console.log("addData_complete_add", res);
      } 
    })
  },
  // 添加玩家昵称
  addNickName: function(label, nickname) {
    label.string = nickname;
  },
  // 添加玩家头像
  addHeadImg: function(sprite, url) {
    let image = wx.createImage();
    image.onload = function() {
      let texture = new cc.Texture2D();
      texture.initWithElement(image);
      texture.handleLoadedTexture();
      sprite.spriteFrame = new cc.SpriteFrame(texture);
    };
    image.src = url;
  },

  _updaetSubDomainCanvas() {
    if (!this.tex) {
      return;
    }
    var openDataContext = wx.getOpenDataContext();
    var sharedCanvas = openDataContext.canvas;
    this.tex.initWithElement(sharedCanvas);
    this.tex.handleLoadedTexture();
    this.paneDisplay.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(this.tex);
  },

  update() {
    this._updaetSubDomainCanvas();
  },
  // 替换成 二级页面 难度选择
  toPaneLv1st: function() {
    this.paneStart.x = 960;
    this.paneLv1st.play();
    cc.log("替换成 二级页面 难度选择");
  },
  // 打开卷抽 之后打开三级难度选择
  // toPaneLv2nd: function() {
  //   this.paneLv2nd.active = true;
  //   this.reelAnimation.play();
  //   cc.log("替换成 三级页面 难度选择");
  // },
  // 打开卷抽 第一阶段 之后打开三级难度选择
  toPaneLv2ndOne: function() {
    this.paneLv2nd.active = true;
    this.reelAnimation.play();
    this.btnLv = 1;
    cc.log("替换成 三级页面 难度选择",this.btnLv);
  },
  // 打开卷抽 第一阶段 之后打开三级难度选择
  toPaneLv2ndTwo: function() {
    this.paneLv2nd.active = true;
    this.reelAnimation.play();
    this.btnLv = 2;
    cc.log("替换成 三级页面 难度选择",this.btnLv);
  },
  // 打开卷抽 第一阶段 之后打开三级难度选择
  toPaneLv2ndThr: function() {
    this.paneLv2nd.active = true;
    this.reelAnimation.play();
    this.btnLv = 3;
    cc.log("替换成 三级页面 难度选择",this.btnLv);
  },
  // 打开三级难度选择
  toPaneLv3rd: function() {
    this.paneLv3rd.active = true;
  },
  // 关闭二级难度选择 替换成主界面
  toCloseLv1st: function() {
    this.btnLv = 0;
    this.paneLv1st.reversePlay();
    cc.log("替换成 主页面",this.btnLv);
  },
  // 隐藏2级界面选择
  toCloseLv2nd: function() {
    this.paneLv2nd.active = false;
    cc.log("隐藏2级选择");
  },
  // 隐藏三级界面选择
  toCloseLv3rd: function() {
    this.paneLv3rd.active = false;
    this.reelAnimation.reversePlay();
    cc.log("隐藏3级选择");
  },
  // 打开商店界面
  toShop: function() {
    this.shopDisplay.active = true;
    console.log('打开商店');
  },
  // 关闭商店界面
  toCloseShop: function() {
    this.shopDisplay.active = false;
    console.log('关闭商店界面');
    this.getData(this.OPENID);
  },
  // 显示排行版
  toRank: function() {
    // 子域加载排行版
    wx.postMessage({
      message: 'rankPage',
    });
    var seq = cc.moveTo(1, cc.v2(0, 0));
    this.paneDisplay.runAction(seq);
    this.closePaneBtn.active = true;
    this.block.active = true;
    console.log("显示排行版");
  },
  // 隐藏排行版
  toCloseRank: function() {
    var seq = cc.moveTo(1, cc.v2(0, 700));
    this.paneDisplay.runAction(seq);
    this.closePaneBtn.active = false;
    this.block.active = false;
    console.log("隐藏排行版");
    this.getData(this.OPENID);
  }, 
  // 跳转分享
  toShare: function() {
    wx.shareAppMessage({
      title: '分享分享',
      imageUrl: 'http://47.52.252.222:9901/head.jpg',
      success: function (res) {
        console.log("shareAppMessage success:", res);
      },
      fail: function (res) {
        console.log("shareAppMessage fail:", res);
      },
    });
    console.log("跳转分享按钮");
  },
  // 初级场景难度
  toGameScene1: function() {
    this.levelData.setLev(this.btnLv,1);
    cc.log("初级难度");
    this.progressLoading();
  },
  // 终极场景难度
  toGameScene2: function() {
    this.levelData.setLev(this.btnLv,2);
    cc.log("中级难度");
    this.progressLoading();
  },
  // 高级场景难度
  toGameScene3: function() {
    this.levelData.setLev(this.btnLv,3);
    cc.log("高级难度");
    this.progressLoading();
  },
  // 加载进度显示
  progressLoading: function() {
    cc.audioEngine.stopAll();
    this.loadingCoverNode.active = true;
    this.loadingCoverAni.play();
    this.paneLv2nd.active = false;
    this.paneLv3rd.active = false;
    // 预加载进度
    cc.loader.onProgress = function(completedCount, totalCount, item) {
      this.textNum.string = Math.floor(completedCount * 100 / totalCount) + "%";
    }.bind(this);
    // 加载
    cc.director.loadScene('game', null, function() {
      cc.loader.onProgress = null;
    });
  },
});
module.exports = Main;